#include "common/include/stock_common.h"
#include "common/include/stock_update.h"

int main(int argc, char *argv[]) 
{
    int                sock;
    struct sockaddr_in server_addr;
    socklen_t          server_len = sizeof(server_addr);
    stock_update       update;

    (void) signal(SIGPIPE, SIG_IGN);

    memset(&update, 0, sizeof(stock_update));

    update.data.timestamp = time(NULL);
    memcpy(update.ticker, "FSLR", strlen("FSLR"));
    update.data.price = 13934;
    update.data.change = 12;
 
    
    memset(&server_addr, 0, server_len);
    server_addr.sin_family = AF_INET;
    server_addr.sin_port   = htons(STOCK_SERVER_PORT);
    if (inet_aton(STOCK_SERVER_IP, &server_addr.sin_addr) == 0) {
        printf("ERROR: inet_aton\n");
    }

    if ((sock = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP)) < 0) {
        printf("ERROR: socket\n");
    }     

    if (connect(sock, (struct sockaddr *)&server_addr, server_len) < 0) {
        printf("ERROR: connect\n");
    }

    while (1) {        

        update.data.timestamp = time(NULL);

        if (stock_update_send(sock, &server_addr, &update) < 0) {
            close(sock);

            if ((sock = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP)) < 0) {
                printf("ERROR: socket\n");
            }     

            if (connect(sock, (struct sockaddr *)&server_addr, server_len) < 0) {
                printf("ERROR: connect\n");
            }
        }

        usleep(1000000);
    }

    return 0;
}

